from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.commons.utils import JsCode

# 数据准备
cities = ["口红", "面膜", "隔离", "防晒", "精华", "面霜", "眼影", "气垫"]
sales = [9221, 5102, 6571, 5760, 6321, 8612, 2634, 5321]
colors = ["#7BBDD5", "#49A098", "#E66B4C", "#FFC000", "#0097E0", "#0070C0", "#4A5BD1", "#464CAC"]

# 创建Bar对象
bar = Bar(
    init_opts=opts.InitOpts(bg_color="#1A1E43")  # 设置背景颜色
)

# 添加X轴数据
bar.add_xaxis(cities)

# 添加Y轴数据，并设置柱状图样式
bar.add_yaxis(
    "销量",
    sales,
    # 设置柱子宽度
    bar_width='30px',
    # 设置鼠标悬停时的高亮颜色
    emphasis_opts=opts.ItemStyleOpts(
        color=JsCode("""
            new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {offset: 0, color: '#00BFA5'},
                {offset: 1, color: '#00D8FF'}
            ])
        """)
    ),
    # 设置柱子的颜色
    itemstyle_opts=opts.ItemStyleOpts(color=JsCode("""
        function(params) {
            var colors = ['#7BBDD5', '#49A098', '#E66B4C', '#FFC000', '#0097E0', '#0070C0', '#4A5BD1', '#464CAC'];
            return colors[params.dataIndex];
        }
    """)),
    # 设置标签样式
    label_opts=opts.LabelOpts(
        is_show=True,
        position='top',
        formatter=JsCode('function (params) {return params.value;}'),
        background_color=JsCode("""
            function(params) {
                var colors = ['#7BBDD5', '#49A098', '#E66B4C', '#FFC000', '#0097E0', '#0070C0', '#4A5BD1', '#464CAC'];
                return colors[params.dataIndex];
            }
        """),
        padding=[2, 9],  # 调整内边距使标签看起来像一个矩形
        font_size=12,
        color="#fff"  # 文字颜色为白色
    )
)

# 设置全局配置项
bar.set_global_opts(
    title_opts=opts.TitleOpts(
        title="2021年商品销量情况",
        # 设置标题颜色
        title_textstyle_opts=opts.TextStyleOpts(color="#FFFFFF"),
        subtitle="口红销量最好达9221，是眼影最低值2645近3.5倍",
        # 设置副标题颜色
        subtitle_textstyle_opts=opts.TextStyleOpts(color="#FFFFFF")
    ),
    xaxis_opts=opts.AxisOpts(
        axislabel_opts=opts.LabelOpts(color="#FFFFFF"),  # 设置X轴标签颜色
        splitline_opts=opts.SplitLineOpts(is_show=False)  # 去掉X轴网格线
    ),
    yaxis_opts=opts.AxisOpts(
        axislabel_opts=opts.LabelOpts(color="#FFFFFF"),  # 设置Y轴标签颜色
        splitline_opts=opts.SplitLineOpts(
            is_show=True,  # 显示Y轴网格线
            linestyle_opts=opts.LineStyleOpts(type_='dashed', color='#FFFFFF')  # 设置Y轴网格线为虚线
        )
    ),
    legend_opts=opts.LegendOpts(is_show=False)  # 去掉图例
)

# 渲染图表到html文件
bar.render("表4.html")
